package ddd.ajava.chapter2.question7;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import ddd.ajava.util.StringUtil;

/**
 * @author lenovo
 * 反射生成private属性的getter和setter方法
 * 1.获取所有private属性
 * 2.生成get和set方法
 * 3.打印在控制台，测试
 */
public class AutoGenerateGetSet {
	private StringBuilder sb;
	private Class person=Person.class;
	private static final String TAB="\t";
	private static final String BLANK=" ";
	
	public static void main(String[] args) {
		AutoGenerateGetSet auto=new AutoGenerateGetSet();
		auto.generate();
		System.out.println(auto.toString());
	}
	
	private void generate(){
		sb=new StringBuilder();
		Field[] fields=person.getDeclaredFields();
		for(Field f:fields){
			//若是private修饰的属性，进行下面的操作
			if(Modifier.isPrivate(f.getModifiers())){
				String type=f.getType().getSimpleName();
				String fieldName=f.getName();
				this.generateGetter(type, fieldName);
				this.generateSetter(type, fieldName);
			}
		}
	}
	
	private void generateGetter(String type,String fieldName){
		String getterName="get"+StringUtil.firstCharToUpper(fieldName);
		sb.append("\n"+TAB);
		sb.append("public "+type+BLANK+getterName+"(){");
		sb.append("\n"+TAB+TAB+"return "+fieldName+";");
		sb.append("\n"+TAB+"}\n");
	}
	
	private void generateSetter(String type,String fieldName){
		String setterName="set"+StringUtil.firstCharToUpper(fieldName);
		sb.append("\n"+TAB);
		sb.append("public void "+setterName+"("+type+BLANK+fieldName+"){");
		sb.append("\n"+TAB+TAB+"this."+fieldName+"="+fieldName+";");
		sb.append("\n"+TAB+"}\n");
	}
	
	public String toString(){
		return sb.toString();
	}
}
